#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <errno.h>

int main() {
    int newfd, oldfd1, oldfd2, newfd2, nchar;
    char buf[30];
    oldfd1 = open("a.txt", O_RDWR);
    if (oldfd1 < 0) {
        perror("open a.txt failed");
        exit(EXIT_FAILURE);
    }
    oldfd2 = open("b.txt", O_RDWR);
    if (oldfd2 < 0) {
        perror("open b.txt failed");
        close(oldfd1);
        exit(EXIT_FAILURE);
    }
    printf("The oldfd1 file descriptor =%d\n", oldfd1);
    printf("The oldfd2 file descriptor =%d\n", oldfd2);
    
    newfd = dup(oldfd1);
    if (newfd < 0) {
        perror("dup failed");
        close(oldfd1);
        close(oldfd2);
        exit(EXIT_FAILURE);
    }
    printf("The newfd file descriptor =%d\n", newfd);
    
    newfd2 = dup2(oldfd1, 10); // 使用非标准输入输出的描述符，比如10
    if (newfd2 == -1) {
        perror("dup2 failed");
        close(oldfd1);
        close(oldfd2);
        close(newfd);
        exit(EXIT_FAILURE);
    }
    printf("The newfd2 file descriptor =%d\n", newfd2);
    
    nchar = read(newfd2, buf, 28);
    if (nchar == -1) {
        perror("read failed");
        close(oldfd1);
        close(oldfd2);
        close(newfd);
        close(newfd2);
        exit(EXIT_FAILURE);
    }
    buf[nchar] = '\0';
    printf("I have read from a.txt:%s\n", buf);
    
    close(oldfd1);
    close(oldfd2);
    close(newfd);
    close(newfd2);
    return 0;
}
